import Vue from "vue";
import Vuex from "vuex";

//引入用户菜单请求
import { getMenuList } from "@/api";
// 引入allRoutes
import allRoutes from "../router/allRoutes";
// 引入递归函数
import recursionRoutes from "../untils/recursionRoutes";
// 引入动态路由
import dynamicRoutes from "../router/dynamicRoutes";
//引入router
import router from "../router";

Vue.use(Vuex);
//从本地存储中获得userInfo
let userInfo = localStorage.getItem("bms-userInfo") || "{}";
userInfo = JSON.parse(userInfo);
export default new Vuex.Store({
  state: {
    permissionButtons:[],
    userInfo:{},
    menuList: [], //用户的侧边栏菜单
    crumbs: [], //处理面包屑
    dialogVisible:false, //控制dialog显示与隐藏
  },
  mutations: {
    //更改userInfo
    SET_USERINFO(state, payload) {
      state.userInfo = payload;
    },
    SET_MENULIST(state, payload) {
      //设置state中的menuList
      state.menuList = payload;
      // console.log(state.menuList);
      //动态的将路由添加到routes中 核心方法:router.addRoutes(符合用户路由规则的数组)
      //将menuList赋值给dynamicRoutes的Home的children,将dynamicRoutes数组中寻找path为"/"的项赋值给target,
      let target = dynamicRoutes.find(item => item.path === "/");
      // console.log(target);
      // 通过展开拷贝赋值给item.children
      target.children = [...state.menuList];
      // console.log(target.children);
      // console.log(dynamicRoutes);
      //动态添加路由配置
      router.addRoutes(dynamicRoutes);
    },
    //设置面包屑
    SET_CRUMBS(state, payload) {
      state.crumbs = payload;
    },
    SET_USERINFO(state,payload){
      state.userInfo = payload;
    },
    SET_PROMISSIONBUTTON(state,payload){
      state.permissionButtons = payload;
    },
  },
  actions: {
    async FETCH_MENULIST({ commit }) {
      //1.发送请求获取用户菜单数据
      let userMenu = await getMenuList();
      // console.log(userMenu);
      // getMenuList()
      // .then(res=>{
      //   console.log(res);
      // })
      // 2.用递归函数对比allRoutes和请求回来的用户菜单数据对比
      let sideMenu = recursionRoutes(allRoutes, userMenu.data.menuList);
      // console.log(sideMenu);
      // 3.将结果提交给mutation
      commit("SET_MENULIST", sideMenu);
    }
  },
  modules: {}
});
